import { ServerAPI } from "f2e-server3";
import * as fs from 'fs'
import * as path from 'path'
import { ADBFactory, execSafe } from "./utils";

const temp_dir = path.join(__dirname, '../temp')
if (!fs.existsSync(temp_dir)) {
    fs.mkdirSync(temp_dir)
}

export default (adb_factory: ADBFactory) => {
    const install_from_file: ServerAPI = async (__, ctx) => {
        const tempfile = path.join(temp_dir, Date.now() + '.apk')
        ctx.body && fs.writeFileSync(tempfile, ctx.body)
        const info = await adb_factory.installApk(ctx.location.searchParams.get('id') + '', tempfile)
        fs.unlinkSync(tempfile)
        return {
            success: !!info
        }
    }

    const install_from_url: ServerAPI<{id: string, url: string}> = async (body) => {
        const { id, url } = body || {}
        const filename = Date.now() + '.apk'
        const tempfile = path.join(temp_dir, filename)
        // 5分钟下载时间
        await execSafe(`cd ${temp_dir} && wget -o log -O ${filename} ${url}`, 300 * 1000)
        // 1分钟安装时间
        const info = await adb_factory.installApk(id + '', tempfile)
        fs.unlinkSync(tempfile)
        return {
            success: !!info
        }
    }

    const open_app: ServerAPI<{id: string, pkg: string}> = async (body, ctx) => {
        const id = ctx.location.searchParams.get('id') + ''
        const pkg = ctx.location.searchParams.get('pkg')
        const info = await adb_factory.shell(id + '', `monkey -p ${pkg} -v 1`)
        return {
            success: !!info
        }
    }
    const list_packages: ServerAPI = async (_, ctx) => {
        const id = ctx.location.searchParams.get('id') + ''
        const info = await adb_factory.shell(id, `pm list packages`)
        const matches = info.match(/[^\r\n]+/g) || []
        return matches.map(line => line.split(':').pop())
    }
    return {
        install_from_file,
        install_from_url,
        open_app,
        list_packages,
    }
}